<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMusicList, deleteMusic, uploadMusic } from '@/api/music'
import { useRouter } from 'vue-router'
import defaultCover from '@/assets/cover.jpg'
import { useUserProfileStore } from '@/store'
import { baseURL } from '@/utils/request'

const isDragOver = ref(false) // 拖拽状态
const uploadedFiles = ref([]) // 上传的文件列表
const myUploads = ref([]) // 用户上传的音乐列表
const loading = ref(false) // 加载状态
const isUploading = ref(false) // 上传状态

// 选中状态相关
const isAllSelected = ref(false) // 全选状态
const isIndeterminate = ref(false) // 半选状态

const userProfileStore = useUserProfileStore()
// 获取用户上传的音乐列表
const fetchMyUploads = async () => {
  try {
    loading.value = true
    const response = await getMusicList()
    
    console.log(userProfileStore.userInfo.id)
    
    if (response.status === 0) {
      myUploads.value = response.data
      .filter(song => song.userId === userProfileStore.userInfo.id)
      .map(song => ({
        ...song,
        isSelected: false
      }))
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取上传音乐失败:', error)
  } finally {
    loading.value = false
  }
}

// 计算选中的 ID列表
const selectedIds = computed(() => {
  return myUploads.value
    .filter(item => item.isSelected)
    .map(item => item.id)
})

// 删除音乐
const handleDeleteMusic = (id, title) => {
  ElMessageBox.confirm(`确定要删除《${title}》吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 调用接口删除音乐
    const response = await deleteMusic(id)
    if (response.status === 0) {
      ElMessage.success('删除成功')
      fetchMyUploads() // 重新获取列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  })
}

// 拖拽事件
const onDragOver = () => {
  isDragOver.value = true
}

// 拖拽离开事件
const onDragLeave = () => {
  isDragOver.value = false
}

// 拖拽释放事件
const onDrop = (e) => {
  isDragOver.value = false
  const files = e.dataTransfer.files
  addFiles(files)
}

// 文件选择事件
const onFileChange = (e) => {
  const files = e.target.files
  addFiles(files)
  e.target.value = '' // 重置文件输入框
}

// 获取用户上传的文件到上传列表中
const addFiles = (files) => {
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    if (file.type.startsWith('audio/') || file.name.match(/\.(mp3|wav|flac|aac|ogg)$/i)) {
      uploadedFiles.value.push({
        name: file.name,
        size: file.size,
        file: file,
        progress: 0,
        status: '等待上传'
      })
    } else {
      ElMessage.warning('请上传支持的音频格式')
    }
  }
}

// 从上传列表中删除文件
const removeFile = (index) => {
  uploadedFiles.value.splice(index, 1)
}

// 清空上传列表
const clearFiles = () => {
  uploadedFiles.value = []
}

// 开始上传
const startUpload = async () => {
  if (uploadedFiles.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件') 
    return
  }
  
  isUploading.value = true
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    
    // 将所有文件添加到 FormData中
    uploadedFiles.value.forEach(fileItem => {
      if (fileItem.status !== '已完成') {
        fileItem.status = '上传中...'
        fileItem.progress = 0
        formData.append('files', fileItem.file)
      }
    })
    
    // 发送上传请求
    const response = await uploadMusic(formData, (progressEvent) => {
      if (progressEvent.lengthComputable) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        uploadedFiles.value.forEach(file => {
          if (file.status === '上传中...') {
            file.progress = percentCompleted
          }
        })
      }
    })
    
    if (response.status === 0) {
      uploadedFiles.value.forEach(file => {
        if (file.status === '上传中...') {
          file.status = '已完成'
          file.progress = 100
        }
      })
      
      ElMessage.success('文件上传成功')
      setTimeout(() => {
        fetchMyUploads()
      }, 1000)
    } else {
      uploadedFiles.value.forEach(file => {
        if (file.status === '上传中...') {
          file.status = '上传失败'
        }
      })
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    uploadedFiles.value.forEach(file => {
      if (file.status === '上传中...') {
        file.status = '上传失败'
      }
    })
    ElMessage.error('上传失败')
  } finally {
    isUploading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) {
    return bytes + ' B'
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(1) + ' KB'
  } else {
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 处理全选/取消全选
const handleCheckAllChange = (val) => {
  myUploads.value.forEach(item => {
    item.isSelected = val
  })
  isIndeterminate.value = false
}

// 处理单个选择变化
const handleSelectionChange = () => {
  const checkedCount = myUploads.value.filter(item => item.isSelected).length
  isAllSelected.value = checkedCount === myUploads.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < myUploads.value.length
}

// 处理批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 首音乐吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteMusic(selectedIds.value.join(','))
      if (response.status === 0) {
        ElMessage.success('删除成功')
        fetchMyUploads() // 重新获取列表
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  })
}

// 当用户信息突然没有时，重新登录
watch(userProfileStore.userInfo, () => {
  if (userProfileStore.userInfo === null) {
    ElMessage.error('用户信息获取失败，请重新登录')
    router.push('/login')
  }
})

// 当token过期或者无token时，跳回登录页
watch(userProfileStore.token, (newToken) => {
  if (!newToken) {
    router.push('/login')
  }
})

// 挂载时获取用户上传的音乐列表
onMounted(() => {
  fetchMyUploads()
})
</script>

<template>
  <div class="upload">
    <div class="upload-header">
      <h1>音乐上传</h1>
      <p class="upload-desc">分享您的音乐创作，让更多人听到您的声音</p>
    </div>

    <div class="upload-container">
      <!-- 上传区域 -->
      <div class="upload-area" :class="{ 'drag-over': isDragOver }" @dragover.prevent="onDragOver" @dragleave.prevent="onDragLeave" @drop.prevent="onDrop">
        <div class="upload-icon">
          <i class="music-icon">♪</i>
        </div>
        <p class="upload-text">将文件拖放到此处或</p>
        <label for="file-input" class="select-button">选择文件</label>
        <input type="file" id="file-input" accept="audio/*" multiple @change="onFileChange" />
        <p class="upload-tip">支持 MP3, WAV, FLAC 等格式，单个文件不超过 50MB</p>
      </div>

      <!-- 上传列表 -->
      <div class="uploaded-files" v-if="uploadedFiles.length > 0">
        <h2>待上传文件 ({{ uploadedFiles.length }})</h2>
        <div class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
          <div class="file-info">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-size">{{ formatFileSize(file.size) }}</div>
          </div>
          <div class="file-progress">
            <div class="progress-bar">
              <div class="progress" :style="{ width: file.progress + '%' }"></div>
            </div>
            <div class="progress-text">{{ file.status }}</div>
          </div>
          <div class="file-actions">
            <button class="remove-btn" @click="removeFile(index)" :disabled="file.status === '上传中...'">×</button>
          </div>
        </div>

        <div class="upload-actions">
          <button class="upload-button" @click="startUpload" :disabled="isUploading">
            {{ isUploading ? '上传中...' : '开始上传' }}
          </button>
          <button class="clear-button" @click="clearFiles" :disabled="isUploading">清空列表</button>
        </div>
      </div>

      <!-- 上传提示 -->
      <div class="upload-tips">
        <h3>上传须知</h3>
        <ul>
          <li style="color: red; font-weight: bold;">上传的音乐的信息请尽量完整，以免上传不通过</li>
          <li style="color: red; font-weight: bold;">请上传正确的音乐文件，避免通过改名的方式再上传</li>
          <li>请确保您拥有上传内容的版权或授权</li>
          <li>禁止上传有政治敏感、暴力色情等违规内容</li>
        </ul>
      </div>
    </div>

    <!-- 已上传的音乐 -->
    <div class="my-uploads">
      <h2>我的上传</h2>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="myUploads.length === 0" class="no-uploads">
        您还没有上传过音乐，快来分享您的作品吧！
      </div>
      
      <template v-else>
        <!-- 批量操作工具栏 -->
        <div class="batch-actions" v-show="myUploads.length > 0">
          <el-checkbox
            v-model="isAllSelected"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-button 
            type="danger" 
            size="small" 
            :disabled="!selectedIds.length"
            @click="handleBatchDelete"
          >
            删除选中
          </el-button>
        </div>

        <div class="music-list">
          <div class="music-list-header">
            <div class="header-title">标题</div>
            <div class="header-time">上传时间</div>
            <div class="header-size">大小</div>
            <div class="header-action"></div>
          </div>
          
          <!-- 音乐列表 -->
          <div 
            v-for="(item, index) in myUploads" 
            :key="index"
            class="music-item"
          >
            <div class="music-checkbox">
              <el-checkbox v-model="item.isSelected" @change="handleSelectionChange" />
            </div>
            
            <!-- 封面 -->
            <div class="music-cover">
              <img :src="item.coverUrl ? `${baseURL}${item.coverUrl}` : defaultCover" alt="封面">
            </div>

            <!-- 音乐信息 -->
            <div class="music-info">
              <div class="music-title">{{ item.title }}</div>
              <div class="music-album">{{ item.album || '未知专辑' }}</div>
            </div>

            <!-- 上传时间 -->
            <div class="music-time">
              {{ item.uploadTime }}
            </div>

            <!-- 大小 -->
            <div class="music-size">
              {{ item.size }} MB
            </div>

            <!-- 操作 -->
            <div class="music-actions">
              <button class="action-btn delete" @click="handleDeleteMusic(item.id, item.title)">删除</button>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped>
.upload {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  padding-bottom: 90px; /* 增加底部内边距，防止内容被播放器遮挡 */
}

.upload-header {
  margin-bottom: 30px;
}

.upload-header h1 {
  font-size: 24px;
  margin-bottom: 10px;
}

.upload-desc {
  color: #666;
}

.upload-container {
  margin-bottom: 40px;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.upload-area.drag-over {
  border-color: #c20c0c;
  background-color: rgba(194, 12, 12, 0.05);
}

.upload-icon {
  font-size: 40px;
  margin-bottom: 15px;
  color: #c20c0c;
}

.music-icon {
  font-size: 60px;
}

.upload-text {
  margin-bottom: 15px;
  font-size: 16px;
}

.select-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #c20c0c;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 15px;
}

.select-button:hover {
  background-color: #d41717;
}

input[type="file"] {
  display: none;
}

.upload-tip {
  color: #999;
  font-size: 12px;
}

.uploaded-files {
  margin-top: 30px;
}

.uploaded-files h2 {
  font-size: 18px;
  margin-bottom: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.file-progress {
  flex: 2;
  margin: 0 15px;
}

.progress-bar {
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress {
  height: 100%;
  background-color: #c20c0c;
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  color: #666;
}

.file-actions {
  margin-left: 10px;
}

.remove-btn {
  border: none;
  background: none;
  color: #999;
  font-size: 18px;
  cursor: pointer;
}

.remove-btn:hover {
  color: #c20c0c;
}

.upload-actions {
  display: flex;
  justify-content: flex-start;
  margin-top: 20px;
}

.upload-button, .clear-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.upload-button {
  background-color: #c20c0c;
  color: white;
}

.clear-button {
  background-color: #f0f0f0;
  color: #666;
}

.upload-tips {
  margin-top: 30px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.upload-tips h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.upload-tips ul {
  padding-left: 20px;
}

.upload-tips li {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.my-uploads {
  margin-top: 40px;
  margin-bottom: 20px; /* 添加底部外边距 */
}

.my-uploads h2 {
  font-size: 20px;
  margin-bottom: 15px;
}

.music-list {
  width: 100%;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.music-list-header {
  display: flex;
  background-color: #f7f8fa;
  padding: 12px 15px;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
}

.header-title {
  flex: 3;
  margin-left: 85px; /* 为复选框和封面图预留空间 */
}

.header-time {
  flex: 1;
  text-align: center;
}

.header-size {
  flex: 1;
  text-align: center;
}

.header-action {
  width: 100px;
  text-align: center;
}

.music-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.music-item:last-child {
  border-bottom: none;
}

.music-item:hover {
  background-color: #f9f9f9;
}

.music-checkbox {
  margin-right: 15px;
}

.music-cover {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
}

.music-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.music-info {
  flex: 3;
  overflow: hidden;
}

.music-title {
  font-weight: 500;
  font-size: 15px;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.music-album {
  font-size: 13px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.music-time {
  flex: 1;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.music-size {
  flex: 1;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.music-actions {
  width: 100px;
  text-align: center;
}

.action-btn.delete {
  background-color: transparent;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 12px;
  transition: all 0.2s;
}

.action-btn.delete:hover {
  background-color: #f56c6c;
  color: white;
}

/* 添加加载状态样式 */
.loading-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

.no-uploads {
  padding: 40px 0;
  text-align: center;
  color: #666;
  font-size: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 修复批量操作工具栏样式 */
.batch-actions {
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 12px 15px;
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 确保复选框有足够的右边距 */
.batch-actions :deep(.el-checkbox) {
  margin-right: 10px;
}

/* 优化响应式布局 */
@media screen and (max-width: 992px) {
  .music-list-header {
    padding: 10px;
  }
  
  .music-item {
    padding: 10px;
  }
  
  .header-title {
    margin-left: 75px;
  }
  
  .music-title {
    font-size: 14px;
  }
  
  .music-album {
    font-size: 12px;
  }
  
  .music-time, .music-size {
    font-size: 13px;
  }
}

@media screen and (max-width: 768px) {
  .music-list-header {
    display: none; /* 在小屏幕上隐藏表头 */
  }
  
  .music-item {
    flex-wrap: wrap;
    padding: 12px 10px;
    position: relative;
  }
  
  .music-checkbox {
    position: absolute;
    top: 12px;
    left: 10px;
    margin-right: 0;
  }
  
  .music-cover {
    margin-left: 28px; /* 为复选框留出空间 */
  }
  
  .music-info {
    flex: 1;
    min-width: 150px;
  }
  
  .music-time, .music-size {
    flex-basis: 50%;
    text-align: left;
    padding-left: 93px; /* 封面宽度+复选框+边距 */
    margin-top: 8px;
    font-size: 12px;
  }
  
  .music-time::before {
    content: "上传时间: ";
    color: #909399;
  }
  
  .music-size::before {
    content: "大小: ";
    color: #909399;
  }
  
  .music-actions {
    position: absolute;
    top: 12px;
    right: 10px;
    width: auto;
  }
  
  .action-btn.delete {
    padding: 4px 8px;
    font-size: 12px;
  }
}

@media screen and (max-width: 576px) {
  .music-item {
    padding: 10px 8px;
  }
  
  .music-cover {
    width: 40px;
    height: 40px;
  }
  
  .music-info {
    min-width: 100px;
  }
  
  .music-time, .music-size {
    flex-basis: 100%;
    padding-left: 83px;
    margin-top: 4px;
  }
  
  .batch-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .batch-actions .el-button {
    font-size: 12px;
    padding: 6px 10px;
  }
}

/* 优化批量操作在不同屏幕尺寸下的显示 */
@media screen and (max-width: 480px) {
  .batch-actions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .batch-actions .el-checkbox {
    margin-bottom: 10px;
  }
}
</style>